package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.exception.BusinessException;
import com.bwie.common.pojo.dto.UserDto;
import com.bwie.common.pojo.po.UserPo;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.remote.AuthRemoteService;
import com.bwie.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private AuthRemoteService authRemoteService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Result login(UserDto userDto) {
        if(ObjectUtil.isEmpty(userDto)){
            throw new BusinessException(Result.error("参数异常"));
        }
        //查询登录用户是否存在
        UserPo userPo = authRemoteService.login(userDto);
        if(ObjectUtil.isEmpty(userDto)){
            throw new BusinessException(Result.error("请先去注册"));
        }
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent("login:ifabsent:"+userDto.getPassword(), 1, 5, TimeUnit.MINUTES);
        if(!ifAbsent){
            throw new BusinessException(Result.error("正在登录 请稍后"));
        }

        HashMap<String, Object> map = new HashMap<>();
        String userKey = IdUtil.fastSimpleUUID();
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, userPo,30, TimeUnit.MINUTES);
        redisTemplate.delete("login:ifabsent:"+userDto.getPassword());
        return Result.success(token,"登录成功");
    }
}
